    //
//  LessonViewController.m
//  Digital Seamonsters
//
//  Created by Adam Cue on 2/22/11.
//  Copyright Adam Cue 2011.
//
//  This program is licensed and distributed under the terms of the GNU General Public License.  
//	The text for the license can be found in the license.txt file in this project.
//

#import "LessonViewController.h"
#import "DrawingInfo.h"

#define NOTE_VIEW_POPOVER_SIZE          CGSizeMake(320, 339)

static dispatch_queue_t lessonQueue;

@interface LessonViewController (Private)
#pragma mark SetupMethods
- (void)setupAnnotationViews;
- (void)setupNotes;
- (void)setupPopovers;
- (void)setupHelpView;

#pragma mark UserActions
- (void)dismissTutorial;

#pragma mark HelperMethods
- (void)animateInTutorialView;
- (NSURLRequest *)getLesson;
- (void)addDrawViews;
@end

@implementation LessonViewController

@synthesize lessonView = _lessonView;
@synthesize helpView = _helpView;
@synthesize lessonURL = _lessonURL;
@synthesize lessonScrollView = _lessonScrollView;
@synthesize annotationViews = _annotationViews;
@synthesize colorPopover = _colorPopover;
@synthesize notePopover = _notePopover;
@synthesize navigationPopover = _navigationPopover;
@synthesize listOfNotesPopover = _listOfNotesPopover;
@synthesize penWidthPopover = _penWidthPopover;
@synthesize lessonName = _lessonName;
@synthesize thumbnail = _thumbnail;
@synthesize annotationTouchPoints = _annotationTouchPoints;
@synthesize lessonID;

//Initialize with the URL of the lesson, the name of the lesson, and the thumbnail.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil lessonURL:(NSString *)selectedLessonURL name:(NSString *)selectedName thumb:(UIImage *)selectedThumb{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
      if(!lessonQueue) lessonQueue = dispatch_queue_create("com.cachalot.Lesson", NULL);
      self.lessonURL = selectedLessonURL;
      _annotationViews = [[NSMutableArray alloc] initWithCapacity:1];
      self.lessonName = selectedName;
      self.thumbnail = selectedThumb;
   }
   return self;
}

- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
   if(showingImage == NO){
		_lessonView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 929, 704)];
		self.lessonScrollView = [[self.lessonView subviews] objectAtIndex:0];
		self.lessonView.scalesPageToFit = YES;
		self.lessonView.delegate = self;
		self.lessonView.backgroundColor = [UIColor whiteColor];
		[self.view addSubview:self.lessonView];
		self.lessonScrollView.delegate = self;
		[DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading Lesson..." width:160];
      dispatch_async(lessonQueue, ^{
         [_lessonView loadRequest:[self getLesson]];
      });
	}
	showingImage = NO;
}

- (void)viewDidLoad {
   [super viewDidLoad];
	UIBarButtonItem *notesButton = [[UIBarButtonItem alloc] initWithTitle:@"Notes" style:UIBarButtonItemStyleBordered target:self action:@selector(notesClicked:)];
	[self.navigationItem setRightBarButtonItem:notesButton];
	[notesButton release];
}

- (void)viewDidDisappear:(BOOL)animated{
   [super viewDidDisappear:animated];
	if(showingImage == NO){
		[self.lessonView removeFromSuperview];
		self.lessonView.delegate = nil;
		self.lessonView = nil;
	}
	NSError *error;
	[[[MarineFetcher sharedInstance] managedObjectContext] save:&error];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation ==UIInterfaceOrientationLandscapeRight;
}


- (void)dealloc {
	self.lessonView = nil;
   self.helpView = nil;
   self.lessonURL = nil;
   self.lessonScrollView = nil;
   self.annotationViews = nil;
   self.colorPopover = nil;
   self.notePopover = nil;
   self.navigationPopover = nil;
   self.listOfNotesPopover = nil;
   self.penWidthPopover = nil;
   self.lessonName = nil;
   self.thumbnail = nil;
   self.annotationTouchPoints = nil;
   
   [super dealloc];
}

#pragma mark SetupMethods
- (void)setupAnnotationViews {
   numberOfPages = self.lessonScrollView.contentSize.width / self.lessonView.width;
	if(((int)(self.lessonScrollView.contentSize.width) % (int)self.lessonView.width) > 5){
		numberOfPages += 1;
		self.lessonScrollView.contentSize = CGSizeMake(self.lessonView.width * numberOfPages, self.lessonScrollView.contentSize.height);
	}
	int i = 0;
	int pageNums = numberOfPages;
	_annotationTouchPoints = [[NSMutableArray alloc] initWithCapacity:numberOfPages];
	int e = 0;
	for(e = 0; e < numberOfPages; e++){
		[self.annotationTouchPoints addObject:[NSArray array]];
	}
   while(pageNums > 0){
      AnnotationView *annotationView = [[AnnotationView alloc] initWithFrame:CGRectMake(self.lessonScrollView.origin.x + i * self.lessonView.width, self.lessonScrollView.origin.y, self.lessonView.width, self.lessonScrollView.contentSize.height)];
		annotationView.delegate = self;
		annotationView.page = i;
		annotationView.tag = i == 0 ? -1 : i;
		if(i == 0){
			[self.lessonScrollView addSubview:annotationView];
			[self.lessonScrollView bringSubviewToFront:annotationView];
		}
		[self.annotationViews addObject:annotationView];
		i++;
		pageNums--;
	}
	NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	NSString *fileDrawing = [NSString stringWithFormat:@"lesson%d", lessonID];
	[fileDrawing stringByAppendingString:@"drawingInfo"];
	path = [path stringByAppendingPathComponent:fileDrawing];
	NSArray *results = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
	int index = 0;
	for(NSMutableArray *touchPoints in results){
		for(DrawingInfo *point in touchPoints){
			[[[self.annotationViews objectAtIndex:index] touchPoints] addObject:point];
		}
		[self.annotationTouchPoints replaceObjectAtIndex:index withObject:[[self.annotationViews objectAtIndex:index] touchPoints]];
		index++;
	}
}

- (void)setupNotes {
   NSFetchRequest *noteRequest = [[NSFetchRequest alloc] init];
	NSEntityDescription *noteEntity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
	[noteRequest setEntity:noteEntity];
	NSError *noteError;
	NSArray *noteFetchResults = [[[MarineFetcher sharedInstance] managedObjectContext] executeFetchRequest:noteRequest error:&noteError];
	if (noteFetchResults == nil) {
		NSLog(@"%@", noteError);
	}
	for(Note *note in noteFetchResults){
		if([note.lessonID intValue] == lessonID){
			NoteTabButton *noteTabButton = [[[NSBundle mainBundle] loadNibNamed:@"NoteTabButton" owner:nil options:nil] objectAtIndex:0];
			noteTabButton.delegate = self;
			noteTabButton.frame = CGRectMake([note.x intValue], [note.y intValue], noteTabButton.frame.size.width, noteTabButton.frame.size.height);
			noteTabButton.noteLabel.text = note.text;
			noteTabButton.note = note;
			[self.lessonScrollView addSubview:noteTabButton];
			[self.lessonScrollView bringSubviewToFront:noteTabButton];
		}
	}
}

- (void)setupPopovers {
   ColorPickerViewController *colorPicker = [[ColorPickerViewController alloc] initWithNibName:@"ColorPickerViewController" bundle:[NSBundle mainBundle] annotationViews:self.annotationViews];
	_colorPopover = [[UIPopoverController alloc] initWithContentViewController:colorPicker];
	colorPicker.colorPopover = self.colorPopover;
	[self.colorPopover setPopoverContentSize:CGSizeMake(247, 296)];
	[colorPicker release];
	PenWidthViewController *penWidth = [[PenWidthViewController alloc] initWithNibName:@"PenWidthViewController" bundle:[NSBundle mainBundle] annotationViews:self.annotationViews];
	_penWidthPopover = [[UIPopoverController alloc] initWithContentViewController:penWidth];
	penWidth.penWidthPopover = self.penWidthPopover;
	[self.penWidthPopover setPopoverContentSize:CGSizeMake(320, 77)];
	[penWidth release];
	NotesTableViewController *notesTable = [[NotesTableViewController alloc] init];
	notesTable.lessonID = lessonID;
	notesTable.dimensionOfPage = self.lessonView.width;
	notesTable.delegate = self;
	_listOfNotesPopover = [[UIPopoverController alloc] initWithContentViewController:notesTable];
	[self.listOfNotesPopover setPopoverContentSize:CGSizeMake(320, 480)];
	[notesTable release];
}

- (void)setupHelpView{
   if(![[NSUserDefaults standardUserDefaults] valueForKey:CACHALOT_LESSON_TUTORIAL_KEY]){
      _helpView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 1024.0, 704.0)];
      self.helpView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.66];
      UIImageView * lessonsHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(37.0, 69.0, 266.0, 225.0)] autorelease];
      lessonsHelpView.image = [UIImage imageNamed:@"lessons-help"];
      lessonsHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:lessonsHelpView];
      UIImageView * notesLessonHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(629.0, 0.0, 319.0, 168.0)] autorelease];
      notesLessonHelpView.image = [UIImage imageNamed:@"notes-lesson-help"];
      notesLessonHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:notesLessonHelpView];
      UIImageView * annotationToolsLessonHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(629.0, 385.0, 317.0, 263.0)] autorelease];
      annotationToolsLessonHelpView.image = [UIImage imageNamed:@"annotation-tools-lesson-help"];
      annotationToolsLessonHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:annotationToolsLessonHelpView];
      UITapGestureRecognizer * hideTutorialTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissTutorial)];
      [self.helpView addGestureRecognizer:hideTutorialTap];
      [hideTutorialTap release];
      UILabel * tutorialLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
      tutorialLabel.text = @"Tap anywhere to dismiss tutorial";
      tutorialLabel.textColor = [UIColor whiteColor];
      tutorialLabel.backgroundColor = [UIColor clearColor];
      tutorialLabel.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:44.0];
      [tutorialLabel sizeToFit];
      tutorialLabel.center = self.helpView.center;
      [self.helpView addSubview:tutorialLabel];
      self.helpView.alpha = 0.0;
   }
}

#pragma mark UserActions
- (void)dismissTutorial {
   [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:CACHALOT_LESSON_TUTORIAL_KEY];
   [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveLinear 
                    animations:^{
                       self.helpView.alpha = 0.0;
                    } completion:^(BOOL finished){
                       [self.helpView removeFromSuperview];
                       self.helpView = nil;
                    }];
}

#pragma mark HelperMethods
- (void)animateInTutorialView {
   if(![[NSUserDefaults standardUserDefaults] valueForKey:CACHALOT_LESSON_TUTORIAL_KEY]){
      [self.view addSubview:self.helpView];
      [UIView animateWithDuration:0.4 delay:1.0 options:UIViewAnimationCurveLinear
                       animations:^{
                          self.helpView.alpha = 1.0;
                       }completion:nil];
   }
}

- (NSURLRequest *)getLesson {
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.lessonURL]];
	return request;
}

- (void)addDrawViews{
	int page = (int) (self.lessonScrollView.contentOffset.x / self.lessonView.width);
	if(page == previousPage)
		return;
	previousPage = page;
	int nextPage = page + 1;
	for(UIView *subview in self.lessonScrollView.subviews){
		if([subview class] == [AnnotationView class]){
			if((page == 0 && subview.tag != -1) && subview.tag != nextPage){
				[subview removeFromSuperview];
			}
			else if(page != 0 && subview.tag != page && subview.tag != nextPage){
				[subview removeFromSuperview];
			}
		}
	}
	if(page == 0 && [self.lessonScrollView viewWithTag:-1] == nil){
		[self.lessonScrollView addSubview:[self.annotationViews objectAtIndex:page]];
		[self.lessonScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:page]];
	}
	else if([self.lessonScrollView viewWithTag:page] == nil){
		[self.lessonScrollView addSubview:[self.annotationViews objectAtIndex:page]];
		[self.lessonScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:page]];
	}
	if([self.lessonScrollView viewWithTag:nextPage] == nil && nextPage < [self.annotationViews count]){
		[self.lessonScrollView addSubview:[self.annotationViews objectAtIndex:nextPage]];
		[self.lessonScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:nextPage]];
	}
	for(UIView *subview in self.lessonScrollView.subviews){
		if([subview class] == [NoteTabButton class]){
			[self.lessonScrollView bringSubviewToFront:subview];
		}
	}
}

#pragma mark IBActions
- (IBAction)note{
	Note *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
	note.lessonID = [NSNumber numberWithInt:lessonID];
	NoteTabButton *noteTabButton = [[[NSBundle mainBundle] loadNibNamed:@"NoteTabButton" owner:nil options:nil] objectAtIndex:0];
	noteTabButton.delegate = self;
	noteTabButton.origin = CGPointMake(self.lessonScrollView.contentOffset.x, self.lessonScrollView.contentOffset.y + self.lessonScrollView.height / 2);
	note.x = [NSNumber numberWithInt:noteTabButton.origin.x];
	note.y = [NSNumber numberWithInt:noteTabButton.origin.y];
	noteTabButton.noteLabel.text = note.text;
	noteTabButton.note = note;
	[self.lessonScrollView addSubview:noteTabButton];
	[self.lessonScrollView bringSubviewToFront:noteTabButton];
	noteTabButton.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
   [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionCurveLinear 
                    animations:^{
                       noteTabButton.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
                    }
                    completion:^(BOOL finished) {
                       [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionCurveLinear
                                        animations:^{
                                           noteTabButton.transform = CGAffineTransformIdentity;
                                        }
                                        completion:nil];
                    }];
}

- (IBAction)highlightClicked:(id)sender{
	if(self.lessonScrollView.scrollEnabled || sketchingActive || eraseActive){
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightActive"] forState:UIControlStateNormal];
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		highlighterActive = YES;
		sketchingActive = NO;
		eraseActive = NO;
		self.lessonScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = YES;
			annotationView.highlighting = YES;
			annotationView.shouldErase = NO;
		}
	}
	else{
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		highlighterActive = NO;
		self.lessonScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
}

- (IBAction)sketchClicked:(id)sender{
	if(self.lessonScrollView.scrollEnabled || highlighterActive || eraseActive){
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawActive"] forState:UIControlStateNormal];
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		sketchingActive = YES;
		highlighterActive = NO;
		eraseActive = NO;
		self.lessonScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = YES;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
	else{
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		sketchingActive = NO;
		self.lessonScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
}

- (IBAction)eraseClicked:(id)sender{
	if(self.lessonScrollView.scrollEnabled || highlighterActive || sketchingActive){
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseActive"] forState:UIControlStateNormal];
		eraseActive = YES;
		highlighterActive = NO;
		sketchingActive = NO;
		self.lessonScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldErase = YES;
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
		}
	}
	else{
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		eraseActive = NO;
		self.lessonScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldErase = NO;
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
		}
	}
}

- (IBAction)colorClicked:(id)sender{
	[self.colorPopover presentPopoverFromRect:[sender frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)widthClicked:(id)sender{
	[self.penWidthPopover presentPopoverFromRect:[sender frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)notesClicked:(id)sender{
	[self.listOfNotesPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)clear{
	UIAlertView *clearView = [[[UIAlertView alloc] initWithTitle:@"Clear Annotations?" message:@"Are you sure you want to remove all your annotations from this reading?  Notes will not be deleted." delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil] autorelease];
	[clearView show];
}

#pragma mark UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
	self.lessonScrollView.pagingEnabled = YES;
	self.lessonScrollView.bounces = NO;
   [self setupAnnotationViews];
	[self setupNotes];
	[self setupPopovers];
   [self setupHelpView];
   [self animateInTutorialView];
    
	[DSBezelActivityView removeViewAnimated:YES];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
   NSString* urlString = [[request URL] absoluteString];
   if([urlString hasPrefix:@"image:"]) {
      NSString *context = [NSString stringWithFormat:@"%@%@", @"http://", [urlString substringFromIndex:8]];
		FullScreenMegafaunaViewController *fullScreenMegafaunaView = [[[FullScreenMegafaunaViewController alloc] init] autorelease];
		fullScreenMegafaunaView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
      fullScreenMegafaunaView.delegate = self;
		[self presentModalViewController:fullScreenMegafaunaView animated:YES];
		fullScreenMegafaunaView.fullImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:context]]];
		fullScreenMegafaunaView.captionView.hidden = YES;
		showingImage = YES;
      return NO;
   }
	else{
      return YES;
   }
}

#pragma mark FullScreenMegafaunaViewControllerDelegate
- (void)closeButtonPressed{
   [self dismissModalViewControllerAnimated:YES];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[self addDrawViews];
}

#pragma mark NotesTableViewControllerDelegate
- (void)noteClicked:(Note *)note{
	int x = [note.x intValue];
	x = (x / self.lessonView.width) * self.lessonView.width;
	self.lessonScrollView.contentOffset = CGPointMake(x, self.lessonScrollView.contentOffset.y);
	[self addDrawViews];
	[self.listOfNotesPopover dismissPopoverAnimated:YES];
}

- (void)allNotesEmailed:(NSString *)notesText{
	[self.listOfNotesPopover dismissPopoverAnimated:YES];
	MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
	mailVC.mailComposeDelegate = self;
	[mailVC setSubject:[NSString stringWithFormat:@"%@ Notes", self.lessonName]];
	NSString *notes = [NSString stringWithFormat:@"<strong>Here are all the notes for %@:</strong><br /><br />%@", self.lessonName, notesText];
	[mailVC setMessageBody:notes isHTML:YES];
	[self presentModalViewController:mailVC animated:YES];
	[mailVC release];
}

#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark AnnotationViewDelegate
- (void)saveDrawing:(NSMutableArray *)touchPoints atPage:(int)page{
	[self.annotationTouchPoints replaceObjectAtIndex:page withObject:touchPoints];
	NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	NSString *fileDrawing = [NSString stringWithFormat:@"lesson%d", lessonID];
	path = [path stringByAppendingPathComponent:fileDrawing];
	[NSKeyedArchiver archiveRootObject:self.annotationTouchPoints toFile:path];
}

#pragma mark NoteTabButtonDelegate
- (void)noteEmailed:(NSString *)text{
	[self.notePopover dismissPopoverAnimated:YES];
	MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
	mailVC.mailComposeDelegate = self;
	[mailVC setSubject:[NSString stringWithFormat:@"%@ Notes", self.lessonName]];
	NSString *notes = [NSString stringWithFormat:@"<strong>Here is a note for %@:</strong><br /><br />%@", self.lessonName, text];
	[mailVC setMessageBody:notes isHTML:YES];
	[self presentModalViewController:mailVC animated:YES];
	[mailVC release];
}

- (void)noteDeleted:(Note *)note{
	[[[MarineFetcher sharedInstance] managedObjectContext] deleteObject:note];
	[self.notePopover dismissPopoverAnimated:YES];
}

- (void)showNote:(NSString *)text button:(NoteTabButton *)tabButton{
	NoteViewController *noteVC = [[NoteViewController alloc] initWithNibName:nil bundle:[NSBundle mainBundle] text:text];
	noteVC.delegate = tabButton;
	if(self.notePopover == nil){
		_notePopover = [[UIPopoverController alloc] initWithContentViewController:noteVC];
	}
	else {
		self.notePopover.contentViewController = noteVC;
	}
	self.notePopover.popoverContentSize = NOTE_VIEW_POPOVER_SIZE;
	[self.notePopover presentPopoverFromRect:tabButton.frame inView:self.lessonScrollView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
	[noteVC release];
	
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex != 0){
		for(AnnotationView *annotationView in self.annotationViews){
			[annotationView clear];
		}
	}
}

@end
